<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/22
 * Time: 12:06
 */

namespace app\api\controller;


use app\admin\model\Coupon;
use app\api\model\CouponMoving;
use app\common\controller\ReturnCode;
use think\Controller;
use think\Request;

class Moving extends Controller
{
    function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this -> openId = $request -> param('openid');
        $this -> couponId = $request -> param('couponid');
    }

    //列表
    public function index(){
        $res = Coupon::all();
        if($res){
            return json(['code'=>0,'msg'=>ReturnCode::$return_code[0],'data'=>$res]);
        }
        return json(['code'=> 5,'msg'=> ReturnCode::$return_code[5]]);
    }

    //领取
    public function moving(){

        if(empty($this->openId) || empty($this->couponId)){
            return json(['code' => 2, 'msg'=>ReturnCode::$return_code[2]]);
        }
        $couponData = Coupon::where('coupon_id','=',$this->couponId)->find();
        if($couponData){
            $data = ['openid' => $this->openId,'coupon_uuid' => $couponData['coupon_uuid']];
            $has = CouponMoving::where($data)->find();
            if($has){
                return json(['code' => 23,'msg'=>ReturnCode::$return_code[23]]);
            }
            $res = CouponMoving::create($data);
            if($res){
                return json(['code'=>0,'msg'=>ReturnCode::$return_code[0]]);
            }
            return json(['code'=> 5,'msg' => ReturnCode::$return_code[5]]);
        }
        return json(['code'=> 10,'msg'=>ReturnCode::$return_code[10]]);

    }


    //领取列表
    public function movinglist(){
        if(empty($this->openId)){
            return json(['code' => 2,'msg' => ReturnCode::$return_code[2]]);
        }
        $where = ['openid' => $this->openId];
//        $res = CouponMoving::get($where)->coupon;
        $res = CouponMoving::where($where)-> select();

        foreach ($res as $key => $val){
            $val['coupon'] = Coupon::where('coupon_uuid','=',$val['coupon_uuid'])->find();
            $res[$key] = $val;
        }

//        die;

        if($res){
            return json(['code' => 0, 'msg' => ReturnCode::$return_code[0],'data'=>$res]);
        }
        return json(['code'=> 1,'msg' => ReturnCode::$return_code[1]]);
    }

}